<template>
  <div class="container">
    <div class="app-container">
      <el-tree :expand-on-click-node="false" :default-expand-all="true" :data="depts" :props="defaultProps">
        <template v-slot="{data}">
          <el-row style="width: 100%;height: 40px;" type="flex" justify="space-between" align="middle">
            <el-col>{{ data.name }}</el-col>
            <el-col :span="4">
              <span class="tree-manager">{{ data.managerName }}</span>
              <el-dropdown @command="handleCom($event,data.id)">
                <!-- 显示区域内容 -->
                <span class="el-dropdown-link">
                  操作<i class="el-icon-arrow-down el-icon--right" />
                </span>
                <!-- 下拉菜单选项 -->
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="add">添加子部门</el-dropdown-item>
                  <el-dropdown-item command="edit">编辑部门</el-dropdown-item>
                  <el-dropdown-item command="del">删除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown></el-col>

          </el-row></template>

      </el-tree></div>
    <addDept ref="addDept" :show-dialog.sync="showDialog" :current-node-id="currentNodeId" @success="getDepartment" /></div></template>
<script>
import { getDeptList, delDept } from '@/api/department'
import { transListToTreeData } from '@/utils/index'

import addDept from './components/add-dept.vue'
export default {
  name: 'Department',
  components: {
    addDept
  },
  data() {
    return {
      currentNodeId: null,
      showDialog: false,
      depts: [
      ],
      defaultProps: {
        label: 'name',
        children: 'children'
      }

    }
  },
  created() {
    this.getDepartment()
  },
  methods: {
    async getDepartment() {
      // 调用获取组织部门接口
      const res = await getDeptList()
      // 对数据进行递归处理
      this.depts = transListToTreeData(res, 0)
    },
    handleCom(type, id) {
      if (type === 'add') {
        this.showDialog = true
        this.currentNodeId = id
      } else if (type === 'edit') {
        this.showDialog = true
        this.currentNodeId = id
        // nextTick把同步变为异步代码
        this.$nextTick(() => {
          this.$refs.addDept.addDeptDetail()
        })
      } else {
        // 删除提示
        this.$confirm('您确定要删除此部门吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          // 调用删除接口
          await delDept(id)
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          // 重新拉取数据
          this.getDepartment()
        })
      }
    }
  }
}
</script>
<style scoped>
.app-container{
  padding:40px 150px ;
}
.tree-manager {
  width: 50px;
  display: inline-block;
  /* margin: 10px; */
  margin-right: 30px;
}
.el-dropdown-link{
  margin-left: 10px;
}
</style>
